let sourceCanvas = document.getElementById("sourceImage");
let soruceCtx = sourceCanvas.getContext("2d");
let openButton = document.getElementById("openFile");
let imageSizeEle = document.getElementById("imageSize");
let hoverModalEle = document.getElementById("hoverModal");
let hoverPosEle = document.getElementById("pos")
let hoverValueEle = document.getElementById("value")
let crossSectionCanvas = document.getElementById("crossSectionCanvas")
let crossSectionCtx = crossSectionCanvas.getContext("2d")
let imageHeight, imageWidth, styleHeight, styleWidth, channels, bitDepth
let imageReader
let iscrossSectionCanvasUpdate = true
async function openFileHandler(e) {
    const pickerOpts = {
        types: [
            {
                description: "Images",
                accept: {
                    "image/*": [".png", ".jpeg", ".jpg", ".tiff"],
                },
            },
        ],
        excludeAcceptAllOption: true,
        multiple: false,
        startIn: 'desktop'
    };
    [fileHandle] = await window.showOpenFilePicker(pickerOpts);
    const file = await fileHandle.getFile();
    const url = URL.createObjectURL(file);
    // let image = new Image()
    // image.onload = async () => {
    //     imageHeight = image.height
    //     imageWidth = image.width
    //     sourceCanvas.width = imageWidth
    //     sourceCanvas.height = imageHeight
    //     styleWidth = Math.min(1000, imageWidth)
    //     styleHeight = styleWidth / imageWidth * imageHeight
    //     sourceCanvas.style.width = styleWidth + "px"
    //     sourceCanvas.style.height = styleHeight + "px"
    //     soruceCtx.drawImage(image, 0, 0)
    //     imageSizeEle.textContent = `Size (W*H) : ${imageWidth} * ${imageHeight}; BitDepth: ${imageReader.bitDepth}, Channel: ${imageReader.channels}}`
    // }
    // image.src = url
    imageReader = await IJS.Image.load(url);
    channels = imageReader.channels
    bitDepth = imageReader.bitDepth
    imageHeight = imageReader.height
    imageWidth = imageReader.width
    sourceCanvas.width = imageWidth
    sourceCanvas.height = imageHeight
    styleWidth = Math.min(1000, imageWidth)
    styleHeight = styleWidth / imageWidth * imageHeight
    sourceCanvas.style.width = styleWidth + "px"
    sourceCanvas.style.height = styleHeight + "px"
    let imgData = soruceCtx.createImageData(imageWidth, imageHeight);
    let max, min
    if (channels == 1) {
        for (let i = 0; i < imageHeight * imageWidth; i++) {
            let pix = imageReader.getPixel(i)[0]
            if (!max && !isNaN(pix)) {
                max = min = pix
                continue
            }
            if (isNaN(pix)) continue
            max = pix > max ? pix : max
            min = pix < min ? pix : min
        }
    }

    for (let h = 0; h < imageHeight; h++) {
        for (let w = 0; w < imageWidth; w++) {
            let i = h * imageWidth + w
            let pix = imageReader.getPixelXY(w, h)
            if (channels == 1) {
                if (isNaN(pix[0])) {
                    imgData.data[i * 4 + 0] = 0;
                    imgData.data[i * 4 + 1] = 0;
                    imgData.data[i * 4 + 2] = 0;
                    imgData.data[i * 4 + 3] = 255;
                    continue
                }
                pix = bitDepth <= 8 ? pix[0] : Math.round((pix[0] - min) / (max - min) * 254)
                imgData.data[i * 4 + 0] = pix;
                imgData.data[i * 4 + 1] = pix;
                imgData.data[i * 4 + 2] = pix;
                imgData.data[i * 4 + 3] = 255;
                continue
            }
            if (channels == 3) {
                imgData.data[i * 4 + 0] = pix[0];
                imgData.data[i * 4 + 1] = pix[1];
                imgData.data[i * 4 + 2] = pix[2];
                imgData.data[i * 4 + 4] = 255;
                continue
            }
            if (channels == 4) {
                imgData.data[i * 4 + 0] = pix[0];
                imgData.data[i * 4 + 1] = pix[1];
                imgData.data[i * 4 + 2] = pix[2];
                imgData.data[i * 4 + 3] = pix[3];
                continue
            }
        }
    }
    soruceCtx.putImageData(imgData, 0, 0);
    console.log(imageReader)
}

function canvasHoverHandler(e) {
    let offsetX = e.offsetX
    let offsetY = e.offsetY
    let x = offsetX / styleWidth * imageWidth
    let y = offsetY / styleHeight * imageHeight
    hoverModalEle.style.zIdex = 99999
    hoverModalEle.style.position = "fixed"
    hoverModalEle.style.display = "block"
    hoverModalEle.style.left = e.clientX + 20 + "px"
    hoverModalEle.style.top = e.clientY + 20 + "px"
    hoverModalEle.style.background = "#f0f0f0"
    hoverModalEle.style.padding = "5px"
    hoverModalEle.style.border = "1px solid #0f0f0f"
    hoverPosEle.textContent = `Pos (x, y) : ${x.toFixed(3)}, ${y.toFixed(3)}`
    if (!imageReader) return
    roundX = Math.round(x)
    roundY = Math.round(y)
    let pix = imageReader.getPixelXY(roundX, roundY)
    let s = ""
    for (i = 0; i < channels; i++) {
        s += `${bitDepth > 8 ? pix[i].toFixed(4) : pix[i]}`
        if (i != channels - 1) s += ", "
    }
    hoverValueEle.textContent = `Value: ${s}`
    // document.addEventListener('keyup', (e) => {
    //     if (e.code === "KeyS") {
    //         e.preventDefault()
    //         iscrossSectionCanvasUpdate = !iscrossSectionCanvasUpdate
    //     }
    // })
    sourceCanvas.addEventListener("click", toggleIscrossSectionCanvasUpdate)
    if (iscrossSectionCanvasUpdate) drawCrossSectionCanvas(roundX, roundY)
}

function drawCrossSectionCanvas(x, y, direction = "x", sizeRatio = 0.3) {
    if (direction == "x") {
        let min = []
        let max = []
        let value = []
        for (let i = 0; i < channels; i++) {
            min.push(NaN);
            max.push(NaN);
        }
        for (w = 0; w < imageWidth; w++) {
            pix = imageReader.getPixelXY(w, y)
            let _value = []
            for (let channel = 0; channel < channels; channel++) {
                let _pix = pix[channel]
                _value.push(_pix)
                if (isNaN(_pix)) {
                    continue
                }
                if (isNaN(min[channel])) {
                    min[channel] = _pix
                    max[channel] = _pix
                    continue
                }
                min[channel] = _pix < min[channel] ? _pix : min[channel]
                max[channel] = _pix > max[channel] ? _pix : max[channel]
            }
            value.push(_value)
        }
        crossSectionCanvas.width = imageWidth
        crossSectionCanvas.height = imageWidth * sizeRatio
        crossSectionCtx.beginPath()
        crossSectionCtx.fillStyle = "white"
        crossSectionCtx.rect(0, 0, crossSectionCanvas.width, crossSectionCanvas.height)
        crossSectionCtx.fill()
        for (i = 0; i < value.length; i++) {
            for (let channel = 0; channel < channels; channel++) {
                let _value = value[i][channel]
                let _min = min[channel]
                let _max = max[channel]
                let _y = crossSectionCanvas.height - (_value - _min) / (_max - _min) * crossSectionCanvas.height

                crossSectionCtx.save()
                crossSectionCtx.beginPath();
                if (isNaN(value[i][channel])) {
                    _y = crossSectionCanvas.height
                    crossSectionCtx.fillStyle = "purple"
                    crossSectionCtx.arc(i, _y, 6, 0, 2 * Math.PI)
                    crossSectionCtx.fill()
                    crossSectionCtx.restore()
                    continue
                }
                if (Math.abs(i - x) < 1) {
                    crossSectionCtx.fillStyle = "red"
                    crossSectionCtx.arc(i, _y, 20, 0, 2 * Math.PI)
                    crossSectionCtx.fill()
                    crossSectionCtx.restore()
                    continue
                }

                crossSectionCtx.fillStyle = "black"
                crossSectionCtx.arc(i, _y, 3, 0, 2 * Math.PI)
                crossSectionCtx.fill()
                crossSectionCtx.restore()
            }

        }
        corssSectionStyleWidth = Math.min(1000, imageWidth)
        corssSectionStyleHeight = corssSectionStyleWidth / crossSectionCanvas.width * crossSectionCanvas.height
        crossSectionCanvas.style.width = corssSectionStyleWidth + "px"
        crossSectionCanvas.style.height = corssSectionStyleHeight + "px"
    }

}

function canvasMouseLeaveHandler() {
    hoverModalEle.style.display = "none"
    sourceCanvas.removeEventListener("click", toggleIscrossSectionCanvasUpdate)
}

function toggleIscrossSectionCanvasUpdate() {
    iscrossSectionCanvasUpdate = !iscrossSectionCanvasUpdate
}

function main() {
    openButton.onclick = openFileHandler
    sourceCanvas.onmousemove = canvasHoverHandler
    sourceCanvas.onmouseleave = canvasMouseLeaveHandler
}
main()